package com.wzh.view;

import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;

import com.wzh.pojo.Contact;
import com.wzh.service.ContactService;
import com.wzh.service.serviceImpl.ContactServiceImpl;

public class AddWindow extends JFrame {

	private static final long serialVersionUID = 1L;

	ContactService pbService = new ContactServiceImpl();

	public AddWindow() {
		this.setTitle("添加联系人");
		int windowWidth = this.getWidth();
		int windowHeight = this.getWidth();
		Toolkit kit = Toolkit.getDefaultToolkit();
		Dimension screenSize = kit.getScreenSize();
		int screenWidth = screenSize.width;
		int screenHeight = screenSize.height;
		this.setLocation(screenWidth / 2 - windowWidth / 2 - 125, screenHeight / 2 - windowHeight / 2 - 250);

		this.setSize(250, 350);
		this.setLayout(null);

		JLabel jlName = new JLabel("姓名:");
		JLabel jlTelephone = new JLabel("电话:");
		JLabel jlAddress = new JLabel("地址:");

		final JTextField jtf_Name = new JTextField();
		final JTextField jtf_Tel = new JTextField();
		final JTextField jtf_Address = new JTextField();

		JButton jbtAdd = new JButton("添加");

		JButton jbtReset = new JButton("重置");
		// 标签 Name宽30 高35 ,其他宽45 高35 输入框统一宽90,高25
		jlName.setBounds(5, 5, 50, 30);
		jtf_Name.setBounds(55, 7, 150, 25);
		jlTelephone.setBounds(5, 70, 45, 30);
		jtf_Tel.setBounds(55, 70, 150, 25);
		jtf_Address.setBounds(55, 130, 150, 25);
		jlAddress.setBounds(5, 190, 45, 30);
		jbtReset.setBounds(20, 250, 70, 25);
		jbtAdd.setBounds(135, 250, 70, 25);

		this.add(jlName);
		this.add(jlTelephone);
		this.add(jlAddress);
		this.add(jtf_Name);
		this.add(jtf_Tel);
		this.add(jtf_Address);

		this.add(jbtAdd);
		this.add(jbtReset);
		jbtAdd.addActionListener(new ActionListener() {
			@Override
			public void actionPerformed(ActionEvent e) {
				if (jtf_Name.getText().equals("") || jtf_Tel.getText().equals("")) {
					JOptionPane.showMessageDialog(null, "输入信息不完整,不能完成添加,至少需要姓名和一个电话号码");
				} else {
					boolean status = pbService.addContact(new Contact(jtf_Name.getText(), jtf_Tel.getText(), jtf_Address.getText()));
					if (status) {
						JOptionPane.showMessageDialog(null, "添加成功!");
						MainView mainView = new MainView();
						mainView.loadData();
					} else {
						JOptionPane.showMessageDialog(null, "添加失败,请重新输入");
					}
				}
			}
		});
		jbtReset.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				jtf_Name.setText("");
				jtf_Tel.setText("");
				jtf_Address.setText("");
			}
		});
		this.setVisible(true);
	}
}
